package com.xiaolong.log.aspectj;

import com.alibaba.fastjson2.JSON;
import com.xiaolong.log.msg.ErrorLogMessage;
import com.xiaolong.log.util.HttpUtil;
import com.xiaolong.log.util.InstanceUtil;
import com.xiaolong.log.util.LogUtil;
import com.xiaolong.log.util.SendUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Method;

@Aspect
public class ErrorLogAspect {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Pointcut("@within(org.springframework.web.bind.annotation.RestController) || " +
            "@within(org.springframework.stereotype.Controller)")
    public void errorLogPointCut() {
    }

    @Around("errorLogPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long l = System.currentTimeMillis();
        try {
            return point.proceed();
        } catch (Throwable t) {
            ErrorLogMessage msg=new ErrorLogMessage();
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            msg.setHttpMethod(HttpUtil.method(request));
            msg.setHttpUrl(HttpUtil.url(request));
            MethodSignature signature = (MethodSignature) point.getSignature();
            Method method = signature.getMethod();
            msg.setClassName(point.getTarget().getClass().getSimpleName());
            msg.setMethodName(method.getName());
            msg.setRequestParam(LogUtil.getRequestParam(point));
            msg.setStartTime(l);
            msg.setRemark(LogUtil.getStackTrace(t));
            msg.setInstanceIp(InstanceUtil.instanceIp());
            msg.setInstanceName(InstanceUtil.instanceName());
            msg.setInstancePort(InstanceUtil.instancePort());
            SendUtil.sendErr(msg);
            throw t;
        }
    }
}
